package com.lkj.controller;

import cn.hutool.core.util.StrUtil;
import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.lkj.utils.*;
import org.springframework.web.bind.annotation.*;


import javax.servlet.http.HttpServletRequest;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;

@RestController
@RequestMapping("/wx")
public class IndexController {

    private static final String token = "xiaojia00";

    @GetMapping("/checkSign")
    public String checkSign(@RequestParam String signature,@RequestParam String timestamp,
                            @RequestParam String nonce,@RequestParam String echostr){

        System.out.println("signature:"+signature);
        System.out.println("timestamp:"+timestamp);
        System.out.println("nonce:"+nonce);
        System.out.println("echostr:"+echostr);


        boolean b = SignUtil.checkSignature(token, signature, timestamp, nonce);

        System.out.println(b);

        return echostr;
    }

    @PostMapping("/checkSign")
    public void getPost(HttpServletRequest request) throws IOException {

        System.out.println(request);

        Map<String, String> map = new HashMap<String, String>();

        // 从 request 中取得输入流
        InputStream inputStream = request.getInputStream();
        // 读取输入流
        ByteArrayOutputStream baos  = new ByteArrayOutputStream();
        int i = -1;
        try {
            while ((i=inputStream.read())!=-1) {
                baos.write(i);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }

        String xmlStr = baos.toString();
        System.out.println(xmlStr);

        JaxbParser jaxbParser = new JaxbParser(WechatRequest.class);
        WechatRequest  req = (WechatRequest) jaxbParser.toObj(xmlStr);
        MsgType msgType = MsgType.valueOf(req.getMsgType());

        switch (msgType) {
            case event:
                dispatchEvent(req);
                break;
            case text:
                onText();
                break;
            default:
                onText();
                break;
        }
    }

    @GetMapping("/index")
    public String index(){

//https请求方式: GET https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=APPID&secret=APPSECRET

        String url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=wx293a983c29afcf2e&secret=e4ce0f4b890e08863d6d5b64de967171";
        String result = HttpUtil.get(url);
        System.out.println(result);


        return result;
    }

    @GetMapping("getCode")
    public String getCode(@RequestParam String code){

        System.out.println(code);
        return "" ;
    }

    private void dispatchEvent(WechatRequest wechatRequest) {

        EventType event = EventType.valueOf(wechatRequest.getEvent());
        switch (event) {
            case SCAN:
                scan(wechatRequest);
                break;
            case subscribe:
                subscribe(wechatRequest);
            default:
                break;
        }

    }

    private void onText(){

    }

    private void subscribe(WechatRequest request){
        String ticket = request.getTicket();
        if (StrUtil.isNotBlank(ticket)) {
            System.out.println("扫描场景二维码事件");
            scan(request);
        }

    }

    private void scan(WechatRequest request){

        String eventKey = request.getEventKey();
        String fromUserName = request.getFromUserName();

        System.out.println(eventKey);

        String url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=wx293a983c29afcf2e&secret=e4ce0f4b890e08863d6d5b64de967171";
        String result = HttpUtil.get(url);
        System.out.println(result);
        JSONObject object = JSONUtil.parseObj(result);
        String token = object.getStr("access_token");

        String templateUrl = "https://api.weixin.qq.com/cgi-bin/message/template/send?access_token="+token;
        System.out.println(templateUrl);
        HashMap<String, Object> paramMap = new HashMap<>();
        paramMap.put("touser", fromUserName);
        paramMap.put("template_id","STpOzCLFeiFwey5iH7LkZS-RPco8yenhKUXnIoAL_u8");
// "color":"#173177"
        HashMap<Object, Object> map1 = new HashMap<>();
        map1.put("value","排队叫号提醒");
        map1.put("color","#173177");

        HashMap<Object, Object> map2 = new HashMap<>();
        map2.put("value","A001");
        map2.put("color","#173177");

        HashMap<Object, Object> map3 = new HashMap<>();
        map3.put("value","2020-12-12 12:12:00");
        map3.put("color","#173177");

        HashMap<Object, Object> map4 = new HashMap<>();
        map4.put("value","请注意叫号信息");
        map4.put("color","#173177");

        HashMap<Object, Object> data = new HashMap<>();
        data.put("first",map1);
        data.put("keyword1",map2);
        data.put("keyword2",map3);
        data.put("remark",map4);

        paramMap.put("data",data);

        String jsonStr = JSONUtil.toJsonStr(paramMap);
        System.out.println(jsonStr);


        String post = HttpUtil.post(templateUrl, jsonStr);
        System.out.println("post:"+post);
        HttpRequest body = HttpRequest.post(url).body(jsonStr);

        System.out.println("body:"+body);
    }
}
